package com.zjuee.base.utils;

import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author wu liang
 * @since 1.0
 */
public final class Base64Utils {

    /**
     * 字节转换
     *
     * @param content
     * @return
     */
    private static byte[] getBytes(String content) {
        return content.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * 字符转换
     *
     * @param bytes
     * @return
     */
    private static String toString(byte[] bytes) {
        return new String(bytes, StandardCharsets.UTF_8);
    }

    public static byte[] encode(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        return Base64.getEncoder().encode(getBytes(content));
    }

    public static byte[] decode(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        return Base64.getDecoder().decode(getBytes(content));
    }

    public static byte[] encode(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        return Base64.getEncoder().encode(bytes);
    }

    public static byte[] decode(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        return Base64.getDecoder().decode(bytes);
    }

    public static String encodeToString(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        return toString(encode(bytes));
    }

    public static String decodeToString(byte[] bytes) {
        if (null == bytes) {
            return null;
        }
        return toString(decode(bytes));
    }


    public static String encodeToString(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        return toString(encode(getBytes(content)));
    }

    public static String decodeToString(String content) {
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        return toString(decode(getBytes(content)));
    }
}
